package com.watson.juc.pc;


/**
 * 线程之间的通信问题，生产者和消费者问题   等待唤醒 通知唤醒
 *
 * 线程 交替执行 AB 操作同一个变量 num= 0
 *  A num+1
 *  B  num -1
 */
public class abc {
    public static void main(String[] args) {
        Data data = new Data();
        new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    data.increment();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"A").start();
        new Thread(() -> {try {
            for (int i = 0; i < 10; i++) {
                data.decrement();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }},"B").start();
        new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    data.increment();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"C").start();
        new Thread(() -> {try {
            for (int i = 0; i < 10; i++) {
                data.decrement();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }},"D").start();
    }
}


class Data{
    //资源类
    private  int num =0;

    public synchronized void  increment() throws InterruptedException {
//        if (num!=0){
        while (num!=0){
            this.wait();
        }
        num++;
        //通知其他线程，+1 完毕
        this.notifyAll();
        System.out.println(Thread.currentThread().getName()+"==>"+num);

    }
    public synchronized void  decrement() throws InterruptedException {
        while (num == 0) {
//        if (num == 0) {
            this.wait();
        }
        num--;
        //通知其他线程，-1完毕
        this.notifyAll();
        System.out.println(Thread.currentThread().getName()+"==>"+num);
    }

}